package cn.lijiajia3515.cairo.auth.config;

import cn.lijiajia3515.cairo.auth.framework.security.jackson2.CairoJackson2Module;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.security.jackson2.CoreJackson2Module;
import org.springframework.security.oauth2.client.jackson2.OAuth2ClientJackson2Module;
import org.springframework.security.oauth2.server.authorization.jackson2.OAuth2AuthorizationServerJackson2Module;
import org.springframework.security.web.jackson2.WebServletJackson2Module;
import org.springframework.security.web.server.jackson2.WebServerJackson2Module;

import javax.security.auth.message.module.ServerAuthModule;


@Slf4j
@EnableCaching
@Configuration(proxyBeanMethods = false)
public class SessionConfig {

	@Bean("springSessionDefaultRedisSerializer")
	public Jackson2JsonRedisSerializer<Object> setDefaultRedisSerializer() {
		ObjectMapper mapper = new ObjectMapper();
		mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
		mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);

		mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);

		mapper.registerModule(new WebServletJackson2Module());
		mapper.registerModule(new WebServerJackson2Module());
		mapper.registerModule(new CoreJackson2Module());
		mapper.registerModule(new CairoJackson2Module());

		mapper.registerModule(new OAuth2AuthorizationServerJackson2Module());
		mapper.registerModule(new OAuth2ClientJackson2Module());
		mapper.registerModule(new JavaTimeModule());

		Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
		serializer.setObjectMapper(mapper);
		return serializer;
	}
}
